<script setup lang="ts">
import { uploads } from "@/api/upload";
import { isExternal, validNumber } from "@/utils/validate";
import { randomTimeSize } from "@/utils/index";
import { ref, toRefs, computed, onMounted } from "vue";
import { useUserStore } from "@/store/modules/user"; // 引入vuex方法
const userStore = useUserStore();
const loading = ref<Boolean>(false);
const files = ref<any>(null);
const fileEle = ref<HTMLInputElement | null>(null);
const emit = defineEmits(["update:modelValue"]);
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  accept: {
    type: String,
    default: "image/*",
  },
  imageWidth: {
    type: Number || String,
    default: 100,
  },
  imageHeight: {
    type: Number || String,
    default: 100,
  },
  isAvatar: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    default: "jpg",
  },
  isIcon:{
    type:Boolean,
    default:true
  }
});
const { accept, modelValue, imageWidth, imageHeight, isAvatar, type } = toRefs(props);
const currentVal = computed({
  get() {
    console.log(modelValue.value);
    return modelValue.value;
  },
  set(val) {
    emit("update:modelValue", val);
  },
});
const classStyle = computed(() => {
  return {
    width: validNumber(imageWidth.value) ? imageWidth.value + "px" : imageWidth.value,
    height: validNumber(imageHeight.value) ? imageHeight.value + "px" : imageHeight.value,
  };
});
const progressSize = ref<number>(0); //上传进度
const text = computed(() => progressSize.value.toFixed(0) + "%"); // 上传进度文字
const readviewImg = ref<string>(); // 预览图片的Base64

const viewUrl = computed(() => {
  return readviewImg.value ? readviewImg.value : currentVal.value;
});

const uploadProgress = (e: any) => {
  const { progress } = e;
  if (!progress) return;
  progressSize.value = Math.ceil(progress * 100) / 100;
};

const getName = () => {
  let file = files.value;
  let date = new Date();
  let dt = date.getFullYear() + "/" + (date.getMonth() + 1);
  let suffixname = file?.name
    ? file?.name.substr(file.name.lastIndexOf(".")).toLowerCase()
    : "";
  let namestr = `musicFestivalImage/${userStore.getUser?.id}/${dt}/${parseInt(
    Math.random() * 100000000 + ""
  )}_${userStore.getUser?.id}${suffixname}`;
  return namestr;
};

const handleUpload = (name = "") => {
  const data: any = {
    file: files.value,
  };
  data.folderName = getName(); // 生成随机时间戳的名字，让后端重命名
  loading.value = true;
  progressSize.value = 0;
  console.log(data);
  uploads(data, uploadProgress)
    .then((res) => {
      let { data } = res;
      currentVal.value = data.url;
      loading.value = false;
    })
    .catch((err) => {
      console.log("失败");
      currentVal.value = "";
      loading.value = false;
    });
};

const uploadFile = (type='') => {
  console.log(props);
  if (props.type === "video") {

    /* #ifdef H5 */
    uni.chooseFile({
      extension: [".mp3", ".mov", ".mp4", ".m4a", ".amr", "wav"],
      success: (chooseImageRes) => {
        console.log(chooseImageRes);
        files.value = chooseImageRes.tempFilePaths[0];
        const name = "/video/" + randomTimeSize();
        handleUpload(name);
      },
    });
    /*#endif */
    /* #ifdef MP-WEIXIN */
    if(type=='video'){
    uni.chooseVideo({
      sourceType: ["camera", "album"],
      success: (chooseImageRes) => {
        files.value = chooseImageRes.tempFilePath;
        const name = "/video/" + randomTimeSize();
        handleUpload(name);
      },
    });
  }else{
    wx.chooseMessageFile({
      count: 1,
      type: "all",
      success: (chooseImageRes) => {
        console.log(chooseImageRes);
        files.value = chooseImageRes.tempFiles[0].path;
        const name = "/video/" + randomTimeSize();
        handleUpload(name);
      },
    });
  }
    /* #endif*/
  } else {
    uni.chooseImage({
      sourceType: ["camera", "album"],
      success: (chooseImageRes) => {
        files.value = chooseImageRes.tempFilePaths[0];
        handleUpload();
      },
    });
  }
};
const handleClose = () => {
  currentVal.value = "";
  readviewImg.value = "";
};

</script>

<template>
  <div class="uploader-body">
    <div
      class="uploader"
      :style="classStyle"
      :class="{ active: currentVal }"
      @click="uploadFile('')"
    >
      <div class="uploadProgress" v-if="loading">
        {{ text }}
      </div>
      <!-- <img v-if="currentVal" :style="classStyle" :src="currentVal" fit="contain" /> -->

      <div v-if="viewUrl" :style="classStyle">

        <img :style="classStyle" :src="viewUrl" fit="contain" />
        <div class="upload-close" @click.stop="handleClose">
         <i class="icon iconfont icon-guanbi1"></i>
        </div>
      </div>
      <div v-else class="uploader-infos">
        <span v-if="isIcon" class="upload-icon"></span>

        <div class="uploader-infos-txt">
          <p class="title"><slot name="title">上传图片</slot></p>
          <p class="title" @click.stop="uploadFile('video')"><slot name="video"></slot></p>
          <p class="info">
            <slot name="info"> </slot>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.hidden {
  display: none;
}
.uploader-body {
  flex: 1;
}
.upload-close {
  position: absolute;
  color: red;
  padding: 2vw;
  right: 0;
  top: 0;
  z-index: 99;
}
.uploader {
  border: 1px dashed #999;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.5s;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  outline: none;
  position: relative;

  &.active {
    border: none;
    &:hover {
      .uploader-refresh {
        opacity: 1;
        transform: scale(1);
      }
    }
  }
  .uploader-refresh {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    background-color: rgba($color: #000000, $alpha: 0.5);
    display: inline-flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    cursor: pointer;
    opacity: 0;
    transform: scale(0);
    transition: all 0.2s;
  }
}
.uploader-infos {
  text-align: center;
  padding: 2vw;
  $w: 30px;
  .upload-icon {
    position: relative;
    width: $w;
    height: $w;

    display: inline-block;
    &:after {
      position: absolute;
      left: 50%;
      width: 2px;
      height: 100%;
      transform: translate(-1px, 0);
      background-color: #333;
      content: "";
      top: 0;
    }
    &:before {
      position: absolute;
      top: 50%;
      left: 0;
      height: 2px;
      transform: translate(0, -1px);
      width: 100%;
      background-color: #333;
      content: "";
    }
  }
  &-txt {
    .title {
      font-weight: 400;
      font-size: 3.6vw;
      margin-top: 2vw;
    }
    p {
    }
    .info {
      margin-top: 2vw;
      color: #888;
      font-size: 3vw;
    }
  }
}
.uploadProgress {
  position: absolute;
  left: 0%;
  top: 0%;
  right: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  flex: 1;
  justify-content: center;
  align-items: center;
  background-color: rgba($color: #000000, $alpha: 0.7);
  color: #fff;
  --circle-text-color: #fff;
  z-index: 20;
  .uni-progress-bar {
    display: none;
  }
}
.upload-close{

}
</style>
